package com.ghsc.ghxc.jsb.ui.live.view.gif

import android.os.Bundle
import android.text.TextUtils
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.dingpaas.interaction.ImSendMessageToGroupReq
import com.alibaba.dingpaas.interaction.ImSendMessageToGroupRsp
import com.aliyun.aliinteraction.InteractionEngine
import com.aliyun.aliinteraction.base.Callback
import com.aliyun.aliinteraction.base.Error
import com.blankj.utilcode.util.GsonUtils
import com.cn.appcore.base.BaseVMFragment
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.utils.GsonUtil
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.CustSignKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.config.UserManager
import com.ghsc.ghxc.jsb.databinding.FragmentPwLiveGiftBinding
import com.ghsc.ghxc.jsb.ui.live.bean.CustImNoticeBean
import com.ghsc.ghxc.jsb.ui.live.bean.GifDataBean
import com.ghsc.ghxc.jsb.ui.live.bean.GifResultDataBean
import com.ghsc.ghxc.jsb.ui.message.view.gif.adapter.GifListAdapter
import com.ghsc.ghxc.jsb.ui.message.view.PayPwdPopViiew
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation

/**
 * 项目：GuoHuaMall
 * 包名：com.ghsc.ghxc.ui.live.view.gif
 * 类名：GiftFragment
 * 创建时间：2023/9/14 22:37
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
class GiftFragment : BaseVMFragment<GiftViewModel, FragmentPwLiveGiftBinding>(R.layout.fragment_pw_live_gift) {
    override fun attachVMClass(): Class<GiftViewModel>? {
        return GiftViewModel::class.java
    }
    override fun lazyLoad() {
    }
    private var imBean: CustImNoticeBean? =null
    //直播id
    private var liveId: String = ""
    //如果是连麦的话。选择的某个主播
    private var checkId: String = ""
    //主播id
    private var anchorId:String =""


    var userResultBean: GifResultDataBean? = null


    companion object {
        fun newInstance(bean: CustImNoticeBean, liveId:String, checkId:String,anchorId:String): GiftFragment {
            val fragment = GiftFragment()
            fragment.imBean = bean
            fragment.liveId = liveId
            fragment.checkId = checkId
            fragment.anchorId = anchorId
            return fragment
        }
    }

    //赠送礼物回调  暂时没有用到
    private var listener:((id:Int,count:Int,isBackpack:Boolean) -> Unit)? = null
    //弹框关闭回调
    private var dismiss:(() -> Unit)? = null
    fun setOnGiveGiftResultListener(listener: ((id:Int,count:Int,isBackpack:Boolean) -> Unit)){
        this.listener = listener
    }
    fun setOnDismissListener(listener: (() -> Unit)){
        this.dismiss = listener
    }



    var price:Double=0.0
    var gid:String= ""
    var gifTitle:String= ""
    var gifImg:String =""
    var downurl :String=""

    var mList: MutableList<GifDataBean> = ArrayList()
    val mAdapter: GifListAdapter by lazy { GifListAdapter() }

    override fun initView(savedInstanceState: Bundle?) {
        binding.rvList.layoutManager = GridLayoutManager(this.context, 4)
        binding.rvList.adapter =mAdapter
        mAdapter.replaceData(mList)
        mAdapter.setOnItemClickListener { adapter, view, position ->
            for (i in mAdapter.data.indices) {
                if (i == position) {
                    mAdapter.data[i].isCheck = true
                    loge("选择的礼物name="+mAdapter.data[i].name+"id="+mAdapter.data[i].gid.toString() +"img="+mAdapter.data[i].images+"url="+mAdapter.data[i].downurl)
                    gifTitle=mAdapter.data[i].name
                    gifImg=mAdapter.data[i].images
                    price=mAdapter.data[i].price.toDouble()
                    if (!TextUtils.isEmpty(mAdapter.data[i].downurl))
                        downurl=mAdapter.data[i].downurl
                    else
                        downurl= ""
                    gid=mAdapter.data[i].gid.toString()

                } else {
                    mAdapter.data[i].isCheck = false
                }
            }
            mAdapter.notifyDataSetChanged()
        }
        //请求礼物列表数据
        mViewModel.onGetGifListMethod("")

    }

    override fun initClickListener() {
        super.initClickListener()
        binding.tvAl.setSingleClickListener {
            dismiss?.invoke()
        }
        binding.btnNext.setSingleClickListener {
            if (!TextUtils.isEmpty(gid)){

                userResultBean?.let {
                    loge("当前"+it.jifen+"xxxx==="+price)
                    if (userResultBean!!.jifen>price){


                        mViewModel.onIsCheckPayPwdMethod()

//
                    }else{
                        showToast("余额不足啦")
                    }
                }
            }else showToast("请选择礼物喔")
        }
    }

    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@GiftFragment) {
                dismissLoading()
                showToast(it)
            }
            againLoginMsg.observe(this@GiftFragment) {
                dismissLoading()
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            onIsCheckPayPwdData.observe(this@GiftFragment){
                val isPwd=it.data as Boolean
                if(isPwd){
                    //送礼物
                    val map: HashMap<String, Any> = HashMap()
                    map["gid"] = gid
                    map["tuid"] = anchorId
                    map["cnt"] =  1
                    map["roomid"] =liveId
                    map["paypassword"] =""
                    val json=  GsonUtil.mapToJsonStrObjEncryption(map)
                    loge("送的礼物="+map.toString())
                    mViewModel.onToGifMethod(json!!)
                }else{
                    XPopup.Builder(requireActivity())
                        .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                        .customHostLifecycle(lifecycle)
                        .autoOpenSoftInput(true)
                        .moveUpToKeyboard(true)
                        .dismissOnTouchOutside(false)
                        .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                        .asCustom(
                            PayPwdPopViiew(requireActivity(),object :
                                PayPwdPopViiew.SublickListener{
                                override fun onAdopt( pwdStr: String) {
                                    //送礼物
                                    val map: HashMap<String, Any> = HashMap()
                                    map["gid"] = gid
                                    map["tuid"] = anchorId
                                    map["cnt"] =  1
                                    map["roomid"] =liveId
                                    map["paypassword"] =pwdStr
                                    val json=  GsonUtil.mapToJsonStrObjEncryption(map)
                                    loge("送的礼物="+map.toString())
                                    mViewModel.onToGifMethod(json!!)
                                }
                            })
                        )
                        .show()
                }
            }
            onToGifData.observe(this@GiftFragment){
                //送礼物成功
                binding.hongbao.text=it.data.data.jifen.toString()
                // 1. 向组内全员发消息
                val req = ImSendMessageToGroupReq()
                req.groupId = imBean!!.groupId
                // 指定消息类型
                req.type = CustSignKey.LIVE_IM_GIF
                // 指定是否跳过安全审核
                req.skipAudit = true
                // 指定是否跳过禁言处理
                req.skipMuteCheck = true
                // 指定发送数据
                req.data = GsonUtils.getGson().toJson(object : HashMap<String?, Any?>() {
                    init {
                        put("userId", UserManager.getUserId())
                        put("userName", UserManager.getUserName())
                        put("userPortrait", UserManager.getUserHead())
                        put("gifGid", gid)
                        put("gifTitle", gifTitle)
                        put("gifImg", gifImg)
//                        put("gifTotalprice", it.data.totalprice)
                        put("gifReceiveId", imBean!!.userId)
                        put("gifSvgUrl",downurl)
                        put("content", "赠送了 $gifTitle")
                    }
                })
                var interactionService = InteractionEngine.instance().interactionService
                interactionService.sendMessageToGroup(req,object :
                    Callback<ImSendMessageToGroupRsp> {
                    override fun onSuccess(p0: ImSendMessageToGroupRsp?) {
                        loge("发送成功")
                    }
                    override fun onError(p0: Error?) {
                    }

                })
            }
            onGetGifListData.observe(this@GiftFragment){
                userResultBean=it.data.data
                binding.hongbao.text=it.data.data.jifen.toString()
                mAdapter.replaceData(it.data.list)
            }
        }
    }

}